I have a function that works as intended when called "onClick" but omits an if statement when called with "onKeyPress".
context
just imagine an input where you can search for food recipes(E.g. "pizza") and you get back a list of recipes from an API with the recipes.
all relevant code explained
↓ This variable stores a boolean value. Checks whether a query from an input is included in any of the titles of the currently displayed list of recipes.
const recipeListHasQuery = recipectx.data.map((recipe: any) => {
return recipe.title.toLowerCase().includes(query);
})
If at least one of the recipe titles in the list does not include the query that we are searching for we can clear the list.
(basically, if you searched for "pizza" and now searching for "burger" and there is no "burger" in any title of the pizza recipes we can clear the list and display burger recipes)
↓ This function works when called "onClick" does not work on "onKeyPress".
const clearView = () => {
console.log('i log on enter')
↓ does not work on enter
if (!recipeListHasQuery.includes(true)) {
const recipeList = document.querySelector(".recipe__list") as HTMLElement;
recipeList!.innerHTML = "";
}
↓ This function works when called "onKeyPress" but omits the if statement
const HandleInputOnKeyPress = (event: React.KeyboardEvent<HTMLInputElement>) => {
if (event.key === "Enter") {
HandleInputChange(event as any); ← this works fine on "Enter"
// clearView(); ← works on "Enter" but omits the if statement
↓ just typing it out does not work either
if (!recipeListHasQuery.includes(true)) {
const recipeList = document.querySelector(".recipe__list") as HTMLElement;
recipeList!.innerHTML = "";
}
}
};
so the problem is that instead of having one list of recipes, with each query, you add a new one
↓ This is the way I'm calling the functions.
<form>
<input onKeyPress={HandleInputOnKeyPress}></input>
<button onClick={clearView}>
Search
</button>
</form>
The function gets called correctly, so this has nothing to do with click and keypress events. The problem is in the logic, particularly in your if statement inside clearView function. You can console.log(recipeListHasQuery.includes(true)) right before the if and debug the logic from there
If you will have difficulties with that, feel free to add your code to jsfiddle, I will help you debug it